import $ = require("jquery");
import artTemplate = require("artTemplate");
import { KVPair, OperableStoreShow } from "../../logic/database/KeyValuePairsDb";
import { OperableDataStoreOnLoad } from "../operable_data_store/onload";
import plan_edit, { EditPlan, ShortPlan } from "./edit";
import iconsvg from "../../logic/page/iconsvg";
import loading from "../../logic/page/loading";
import complate_record, { ComplatePlanRecord } from "./complate_record";

function PageElementBasicEventBind(store: OperableStoreShow) {
    // 待完成任务队列
    let el_WaitCompletionList = $("body .suspension_plan_wait_completion_list");
    el_WaitCompletionList
        .children(".indent")
        .off("click")
        .on("click", function () {
            el_WaitCompletionList.toggleClass("hide");
        });
    iconsvg.onload(el_WaitCompletionList);

    // 当前需完成计划
    let el_ExhibitionArea = $("body .exhibition_area");
    iconsvg.onload(el_ExhibitionArea);

    // 全局工具
    let el_toolbar = $("body .suspension_plan_toolbar");
    el_toolbar.addClass("show");
    el_toolbar
        .find("button.btn.create")
        .off("click")
        .on("click", function () {
            plan_edit.Add(store, function (model: EditPlan) {
                UpdatePage_WaitCompletionList(store);
                UpdatePage_ExhibitionArea(store, [model]);
            });
        });
    iconsvg.onload(el_toolbar);
}

/** 更新页面 - 待完成任务队列 - 部分 */
async function UpdatePage_WaitCompletionList(store: OperableStoreShow) {
    let el_WaitCompletionList = $("body .suspension_plan_wait_completion_list");
    let html_contents = el_WaitCompletionList.children(".contents");
    let template_contents = el_WaitCompletionList.children("script.template_suspension_plan_wait_completion_list");

    // 清空生成内容
    html_contents.empty();
    let plan_infos: ShortPlan[] = (await plan_edit.GetAShortPlanListAsync(store)) || [];
    let html = $(
        artTemplate.render(template_contents.html(), {
            list: plan_infos,
        })
    );
    html_contents.append(html);
    html_contents
        .find(".item")
        .off("click")
        .on("click", async function () {
            let Id = $(this).attr("data-Id");
            let model: EditPlan = await plan_edit.GetPlanAsync(store, Id);
            UpdatePage_ExhibitionArea(store, [model]);
        });
    iconsvg.onload(html_contents);
}

/** 更新页面 - 当前需完成计划 - 部分 */
async function UpdatePage_ExhibitionArea(store: OperableStoreShow, plan_infos: EditPlan[]) {
    let el_ExhibitionArea = $("body .exhibition_area");
    let html_contents = el_ExhibitionArea.children(".contents");
    let template_contents = el_ExhibitionArea.children("script.template_exhibition_area");

    // 清空生成内容
    html_contents.empty();
    let html = $(
        artTemplate.render(template_contents.html(), {
            list: await ConvertExhibitionAreaNeedData(store, plan_infos),
        })
    );
    html.find(".progress .style_selected button.btn.normal")
        .off("click")
        .on("click", function () {
            $(this).parents(".progress").removeClass("list");
        });
    html.find(".progress .style_selected button.btn.list")
        .off("click")
        .on("click", function () {
            $(this).parents(".progress").toggleClass("list");
        });
    html.find(".btn.edit_complate_record")
        .off("click")
        .on("click", function () {
            let self = $(this);

            console.log("button.btn.edit_complate_record.click!!!!!!");
            let planid = self.data("planid");
            let signno = Number(self.data("signno"));
            complate_record.Add(store, planid, signno, function (model: ComplatePlanRecord) {
                let record = self.parents(".record");
                record.find(".time").text(model.Time);
                record.find(".remark").text(model.Remark);
                record.addClass("have");
            });
        });
    html.find(".btn.edit")
        .off("click")
        .on("click", function () {
            let Id = $(this).attr("data-Id");
            plan_edit.Change(store, Id, function (model: EditPlan) {
                UpdatePage_WaitCompletionList(store);
                UpdatePage_ExhibitionArea(store, [model]);
            });
        });
    html_contents.append(html);
    iconsvg.onload(html_contents);
}
async function ConvertExhibitionAreaNeedData(store: OperableStoreShow, plan_infos: EditPlan[]) {
    let datas = [];
    for (let index_plan = 0; index_plan < plan_infos.length; index_plan++) {
        const plan = plan_infos[index_plan];
        let complates = await calc_complate_records(plan);
        datas.push({
            plan,
            complates,
        });
    }
    return datas;

    async function calc_complate_records(plan: EditPlan) {
        let complate_db_datas = (await complate_record.Querys(store, plan.Id)) || [];
        let complate_dict = ArrayToKVPair(complate_db_datas, (item) => item.StepNo.toString());
        let complates = [];
        for (let signno = 1; signno <= plan.NeedComplateCount; signno++) {
            let record: ComplatePlanRecord = complate_dict[signno.toString()];
            if (!record) {
                record = {
                    PlanID: plan.Id,
                    StepNo: signno,
                } as ComplatePlanRecord;
            }
            complates.push(record);
        }
        return complates;
    }
}

function ArrayToKVPair<T>(arr: T[], getKey: (item: T) => string): KVPair {
    var dict:KVPair = {};
    if (!arr || !getKey) {
        return dict;
    }
    for (let index = 0; index < arr.length; index++) {
        const element = arr[index];
        let key = getKey(element);
        dict[key] = element;
    }
    return dict;
}


function PlanOnLoad() {
    OperableDataStoreOnLoad(async (store: OperableStoreShow) => {
        PageElementBasicEventBind(store);

        await UpdatePage_WaitCompletionList(store);

        let plan_infos = await plan_edit.GetAShortPlanListAsync(store);
        if (plan_infos && plan_infos.length > 0) {
            let plan = await plan_edit.GetPlanAsync(store, plan_infos[0].Id);
            await UpdatePage_ExhibitionArea(store, [plan]);
        }

        // 关闭加载中页面
        loading.close();
    });
}

export default {
    PlanOnLoad,
};
